<template>
  <uploader 
    ref="upload" 
    @complete="complete" 
    v-if="isReady"
    :options="options"  
    @file-complete="fileComplete" 
    @file-success="fileSuccess" 
    @file-error="onFileError" 
    @upload-start="fileUploadStart" 
    class="uploader-example">
    <uploader-unsupport></uploader-unsupport>
    <uploader-drop class="drop-box">
      <p class="icon-box"><i class="upload-icon"></i></p>
      <p class="hint">将文件拖到此处或者</p>
      <div class="upload-btns-box">
        <uploader-btn class="btn" :attrs='attrs'>选择文件</uploader-btn>
        <uploader-btn class="btn btn-folder" v-show="!folder" :directory="true">选择文件夹</uploader-btn>
      </div>
    </uploader-drop>
    <uploader-list class="file-lis-box">
    </uploader-list>
  </uploader>
</template>

<script>
  import { getCookie, uuid } from '@/utils/tool'
  import axios from 'axios'
  import { domain } from '@/config'
  import { Base64 } from "js-base64";

  export default {
    data() {
      return {
        buttonVisible: false,
        tempFileLis: [],
        isReady: false,
        uuidStore: uuid(),
        attrs: {},
        options: {
          testChunks: false,
          chunkSize: 1 * 1024 * 1000,
          headers: {
            Authorization: decodeURIComponent(getCookie('login_ticket'))
          }
        },
        uploadId: '',
        myInfo: {}
      }
    },
    watch: {
      relative_path (val) {
        this.initUuid(val)
      }
    },
    props: ['type', 'fileDone', 'relative_path', 'folder', 'accept', 'succeed', 'biz_id'],
    methods: {
      async initUuid (uuid) {
        this.isReady = false
        this.uuidStore = uuid
        // let res = await getUploadServer()
        let url = `${domain}file/`
        let info = await this.$myInfo(this)
        let userId = info && info.id
        this.myInfo = info
        let target = `${url}v1/file/upload`
        this.options.target = target
        this.options.query = file => {
          let relativePath = this.relative_path ? `${this.relative_path}/${file.relativePath}` : file.relativePath
          return {
            userId,
            type: this.type,
            bizId: this.biz_id,
            uploadId: Base64.encode(relativePath),
            relativePath
          }
        }
        this.isReady = true
      },
      fileUploadStart () {
        this.buttonVisible = false
      },
      async merge (arg) {
        let url = `${domain}file/`
        axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
        let data = {
          biz_id: this.biz_id,
          filename: arg.filename,
          relative_path: this.relative_path ? `${this.relative_path}/${arg.relativePath}` : arg.relativePath,
          total_chunks: arg.chunks.length,
          type: this.type,
          upload_id: this.options.query(arg).uploadId,
          user_id: this.myInfo.id
        }
        
        // {
        //   filename: arg.filename,
        //   relativePath,
        //   tenantId: this.organizationId,
        //   type: this.type,
        //   uuid,
        // }
      //  setTimeout(async () => {
        let res = await axios({
          data,
          method: 'post',
          url: `${url}v1/file/merge`,
          headers: {
            Authorization: decodeURIComponent(getCookie('login_ticket')),
            'Content-Type': 'application/json;charset=UTF-8'
          },
        })
        if (res.data && res.data.code == 200) {
          this.$emit('mergeMature', { 'mature': true })
          this.$emit('info', {buttonVisible: this.buttonVisible})
        }
      //  }, 3000)
      },
      async fileSuccess (e) {
        if (e.size) {
          if (e.size > this.options.chunkSize) {
            await this.merge({
              filename: e.name,
              path: this.uuidStore,
              uuid: this.uuidStore,
              relativePath: e.relativePath,
              chunks: e.chunks,
              type: this.type
            })
          }
        } else {
          let temp = []
          e.files.forEach(ele => {
            temp.push(ele)
          });
          this.tempFileLis = temp
        }
        console.log(this.succeed)
        if (this.succeed) {
          this.succeed({
            files: e,
            relative_path: this.relative_path,
            orgId: this.organizationId
          }).then(() => {
            this.buttonVisible = false
            this.$emit('path', {path: this.uuidStore, buttonVisible: this.buttonVisible})
            this.$emit('succeedOver', {path: this.uuidStore, buttonVisible: this.buttonVisible})
          })
          return
        }
        this.buttonVisible = false
        this.$emit('path', {path: this.uuidStore, buttonVisible: this.buttonVisible})
      },
      fileComplete (rootFile) {
        console.log(rootFile)
        this.buttonVisible = false
        this.$emit('info', {buttonVisible: this.buttonVisible})
      },
      complete () {
        this.tempFileLis.forEach(async ele => {
          if (ele.size && ele.size > this.options.chunkSize) {
            console.log(ele.chunks)
            await this.merge({
              filename: ele.name,
              path: this.uuidStore,
              uuid: this.uuidStore,
              relativePath: ele.relativePath,
              chunks: ele.chunks,
              type: this.type
            })
            if (this.succeed) {
              this.succeed({
                files: ele,
                relative_path: this.relative_path,
                orgId: this.organizationId
              }).then(() => {
                this.buttonVisible = false
                this.$emit('path', {path: this.uuidStore, buttonVisible: this.buttonVisible})
                this.$emit('succeedOver', {path: this.uuidStore, buttonVisible: this.buttonVisible})
              })
              return
            }
          }
          if (this.succeed) {
            this.succeed({
              files: ele,
              relative_path: this.relative_path,
              orgId: this.organizationId
            }).then(() => {
              this.buttonVisible = false
              this.$emit('path', {path: this.uuidStore, buttonVisible: this.buttonVisible})
              this.$emit('succeedOver', {path: this.uuidStore, buttonVisible: this.buttonVisible})
            })
            return
          }
        })
        this.tempFileLis = []
        this.buttonVisible = false
        this.$emit('path', {path: this.uuidStore, buttonVisible: this.buttonVisible})
      },
      onFileError () {
        this.buttonVisible = true
      }
    },
    async mounted () {
      let info = await this.$myInfo(this)
      let tenantId = info && info.orgId
      if (this.tenantId) {
        tenantId = this.tenantId
      }
      this.organizationId = tenantId

      if (this.relative_path || this.biz_id) {
        let uuid = this.relative_path || this.biz_id
        this.initUuid(uuid)
      } else {
        this.initUuid(uuid())
      }  
      if (this.accept) {
        this.attrs = {accept: this.accept}
      }    
    }
  }
</script>

<style lang="less" scoped>
.drop-box{
  width: 100%;
  box-sizing: border-box;
  border: 1px dashed #d9d9d9;
  background: #F9F9F9;
  border-radius: 4px;
  transition: all .3s ;
  margin-bottom: 16px;
  .icon-box{
    text-align: center;
    padding-top: 32px;
    i {
      display: block;
      width: 104px;
      height: 96px;
      mask: url(~@/assets/img/upload-icon.svg) no-repeat;
      mask-size: 104px 96px;
      transition: all .3s;
      margin: 0 auto;
      background: #c0c4cc
    }
  }
  .hint{
    text-align: center;
    
  }
  .upload-btns-box{
    text-align: center;
    padding: 14px 0 48px;
    .btn{
      margin: 0 5px;
      color: #606266;
      background: #F5F7FA;
      border: 1px solid #C0C4CC;
      transition: all .3s ;
      padding: 6px 14px;
      border-radius: 4px;
      &:hover{
        color: #FFF;
        background: #4285F4;
        border-color: #4285F4;
      }
    }
    .btn-folder{
      background: #DCDFE6;
      border: 1px solid #DCDFE6;
    }
  }
  &:hover{
    border: 1px dashed #409eff;
    i{
      background: #409eff;
    }
  }
  
}
.file-lis-box{
  line-height: 49px;
  /deep/ .uploader-file-name{
    line-height: 49px;
    width: 40%;
    i{
      margin-right: 20px;
    }
  }
  /deep/ .uploader-file-size{
    width: 18%;
    line-height: 49px;
    margin: 0 2%;
  }
  /deep/ .uploader-file-meta{
    display: none;
  }
  /deep/ .uploader-file-status{
    margin-left: 4%;
    line-height: 49px;
  }
  /deep/ .uploader-file-actions{
    padding-left: 3%;
    box-sizing: border-box;
  }
}
</style>
